/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */

package com.data.structure.link;

/**
 * @author lengleng
 * @date 2018/10/9
 */
public class Link {
    /**
     * 头结点
     */
    Node head;

    /**
     * 插入节点
     *
     * @param data 数据
     */
    public void addNode(int data) {
        Node newNode = new Node(data);
        if (head == null) {
            head = newNode;
            return;
        }
        Node tmp = head;
        while (tmp.next != null) {
            tmp = tmp.next;
        }
        tmp.next = newNode;
    }

    /**
     * @return 链表长度
     * <p>
     * 这种计算的问题没有考虑 最后节点存放数据的问题
     */
    public int length() {
        int length = 0;

        Node temp = head;
        while (temp.next != null) {
            length++;
            temp = temp.next;
        }
        return length;
    }

    /**
     * 删除index位的节点
     * <p>
     * 节点的前节点、后当前节点
     * 1. 为index ==1 ， 第二节点
     * 2. indedx != 1，  前一个节点、当前节点 往后移动
     * <p>
     * 这种算法 必须节点数量大于2
     *
     * @param index 索引位置
     */
    public void deleteNode(int index) {
        if (index == 1) {
            head = head.next;
            return;
        }

        int i = 1;
        Node preNode = head;
        Node curNode = preNode.next;
        while (curNode != null) {
            if (i == index) {
                preNode.next = curNode.next;
                return;
            }
            preNode = curNode;
            curNode = curNode.next;
            i++;
        }
    }


}
